/*
 * Copyright (c) Jan Šlahora (${USER}) - 2011.
 * Created in IntelliJ IDEA 10.5
 */

package MW.CetnostiTaby;

import javax.swing.*;
import javax.swing.plaf.basic.BasicButtonUI;
import java.awt.*;
import java.awt.event.*;

import MW.MW;
import MW.MWClasses;
import sun.plugin2.message.JavaObjectOpMessage;

/**
 * Component to be used as tabComponent;
 * Contains a JLabel to show the text and
 * a JButton to close the tab it belongs to
 */
public class ButtonTabComponent extends JPanel implements MouseListener {
  private final JTabbedPane pane;


  public ButtonTabComponent(final JTabbedPane pane) {

    //unset default FlowLayout' gaps
    super(new FlowLayout(FlowLayout.LEFT, 0, 0));
    // Set System L&Feel
    
    try {
      UIManager.setLookAndFeel(
          UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
      System.err.println("Error when setting Look and Feel");
      JOptionPane.showMessageDialog(null, "Error when setting Look and Feel", "Error", JOptionPane.ERROR_MESSAGE);
    }
    if (pane == null) {
      throw new NullPointerException("TabbedPane is null");
    }
    this.pane = pane;
    setOpaque(false);

    //make JLabel read titles from JTabbedPane
    JLabel label = new JLabel() {
      public String getText() {
        int i = pane.indexOfTabComponent(ButtonTabComponent.this);
        if (i != -1) {
          return pane.getTitleAt(i);
        }
        return null;
      }

      public void setText(String title) {
        int i = pane.indexOfTabComponent(ButtonTabComponent.this);
        if (i != -1) {
          pane.setTitleAt(i, title);
        }
      }

    };

    label.addMouseListener(this);

    add(label);
    //add more space between the label and the button
    label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
    //tab button
    JButton button = new TabButton();
    add(button);
    //add more space to the top of the component
    setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
  }

  @Override
  public void mouseClicked(MouseEvent e) {
    if (e.getButton() == MouseEvent.BUTTON1 || e.getButton() == MouseEvent.BUTTON3) {
      if (e.getSource() instanceof JLabel) {
        int i = pane.indexOfTabComponent(ButtonTabComponent.this);
        pane.setSelectedIndex(i);
      }
    }
    if (e.getButton() == MouseEvent.BUTTON3) {
      if (e.getSource() instanceof JLabel) {
        String stareJmeno = ((JLabel) e.getSource()).getText();
        String noveJmeno = (String) JOptionPane.showInputDialog(null,
            "Nové jméno:",
            "Změna jména",
            JOptionPane.QUESTION_MESSAGE,
            null,
            null,
            stareJmeno);
        //(Component parentComponent, Object message, String title, int messageType)
        if (noveJmeno != null && noveJmeno.length() > 0) {
          //..nastaví nové jméno a změní rozměr záložky
          ((JLabel) e.getSource()).setText(noveJmeno);
          ((JLabel) e.getSource()).setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
          int i = pane.indexOfTabComponent(ButtonTabComponent.this);
          //((JViewport) ((JScrollPane) pane.getComponent(i)).getComponent(0)).getComponent(0).setName(noveJmeno);
          AbstractButton button = (AbstractButton) (((ButtonTabComponent) pane.getTabComponentAt(i)).getComponents()[1]);
          button.setBorderPainted(false);
        }
      }
    }
  }

  @Override
  public void mousePressed(MouseEvent e) {
    //To change body of implemented methods use File | Settings | File Templates.
  }

  @Override
  public void mouseReleased(MouseEvent e) {
    //To change body of implemented methods use File | Settings | File Templates.
  }

  @Override
  public void mouseEntered(MouseEvent e) {
    //To change body of implemented methods use File | Settings | File Templates.
  }

  @Override
  public void mouseExited(MouseEvent e) {
    //To change body of implemented methods use File | Settings | File Templates.
  }

  private class TabButton extends JButton implements ActionListener {
    public TabButton() {
      try {
        // Set System L&F
        UIManager.setLookAndFeel(
            UIManager.getSystemLookAndFeelClassName());
      } catch (Exception e) {
        System.err.println("Error when setting Look and Feel");
        JOptionPane.showMessageDialog(null, "Error when setting Look and Feel", "Error", JOptionPane.ERROR_MESSAGE);
      }
      int size = 17;
      setPreferredSize(new Dimension(size, size));
      setToolTipText("close this tab");
      //Make the button looks the same for all Laf's
      setUI(new BasicButtonUI());
      //Make it transparent
      setContentAreaFilled(false);
      //No need to be focusable
      setFocusable(false);
      setBorder(BorderFactory.createEtchedBorder());
      setBorderPainted(false);
      //Making nice rollover effect
      //we use the same listener for all buttons
      addMouseListener(buttonMouseListener);
      setRolloverEnabled(true);
      //Close the proper tab by clicking the button
      addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
      int i = pane.indexOfTabComponent(ButtonTabComponent.this);
      MW mw = (MW) pane.getRootPane().getParent();

      if (i != -1) {
        pane.remove(i);
      }


      if (pane.getTabCount() == 0) {
        mw.getBtn_open().setEnabled(false);
      } else {
        mw.getBtn_open().setEnabled(true);
      }

      mw.setBtnAnalyseViditelnost();
      mw.setEditorPane1(MWClasses.getJEditorPaneOnActualTab(pane.getSelectedComponent()));
    }

    //we don't want to update UI for this button
    public void updateUI() {
    }

    //paint the cross
    protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g.create();
      //shift the image for pressed buttons
      if (getModel().isPressed()) {
        g2.translate(1, 1);
      }
      g2.setStroke(new BasicStroke(2));
      g2.setColor(Color.BLACK);
      if (getModel().isRollover()) {
        g2.setColor(Color.RED);
      }
      int delta = 6;
      g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1);
      g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1);
      g2.dispose();
    }
  }

  private final static MouseListener buttonMouseListener = new MouseAdapter() {
    public void mouseEntered(MouseEvent e) {
      Component component = e.getComponent();
      if (component instanceof AbstractButton) {
        AbstractButton button = (AbstractButton) component;
        button.setBorderPainted(true);
      }
    }

    public void mouseExited(MouseEvent e) {
      Component component = e.getComponent();
      if (component instanceof AbstractButton) {
        AbstractButton button = (AbstractButton) component;
        button.setBorderPainted(false);
      }
    }
  };
}